package com.gxitsky.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author duhao
 * @version 1.0
 * @date 2020/8/17 17:26
 */
public class MD5Utils {

    /**
     * md5
     *
     * @return
     * @author 杜浩
     * @date 2020/7/11 10:55
     */
    public final static String getMD5(String str) {
        try {
            //创建具有指定算法名称的摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //使用指定的字节数组更新摘要
            md.update(str.getBytes());
            //进行哈希计算并返回一个字节数组
            byte mdBytes[] = md.digest();
            String hash = bytes2HexString(mdBytes, 0, true);
            return hash;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 字节数组转16进制字符串
     * 16进制不区分大小写
     *
     * @param startPos    开始转码字节开始下标
     * @param isLowerCase 转码后是否字母小写
     * @return
     * @author 杜浩
     * @date 2020/7/4 16:59
     */
    public static String bytes2HexString(byte[] packet, int startPos, boolean isLowerCase) {
        StringBuffer sb = new StringBuffer();
        String hex = null;
        for (int i = startPos; i < packet.length; i++) {
            if (isLowerCase)
                hex = Integer.toHexString(packet[i] & 0xFF).toLowerCase();
            else
                hex = Integer.toHexString(packet[i] & 0xFF).toUpperCase();
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
